﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MVC.DAL.Interface;
using NHibernate;
using System.Collections;
using MVC.Common;

namespace MVC.DAL
{
    public class EmployeeDAL 
    {
        public bool Save(EmployeeDTO empDTO)
        {
            ISession session = null;
            ITransaction transaction = null;
            try
            {
                session = NHibernateUtil.OpenSession();
                if (null == session)
                {
                    throw new Exception("No Session created!!!");
                }
                transaction = session.BeginTransaction();
                //string hql = "from DepartmentDTO as dept where dept.DeptId = 1";
                //IQuery query = session.CreateQuery(hql);
                //IList l = query.List();
                //if (l != null && l.Count > 0)
                //    empDTO.Department = (DepartmentDTO)l[0];
                empDTO.Department = session.Get<DepartmentDTO>(1);

                session.SaveOrUpdate(empDTO);
                transaction.Commit();
            }
            catch (Exception e)
            {                
                //Console.WriteLine("Error: " + e.Message);
                //Console.ReadKey();
            }
            finally
            {
                NHibernateUtil.CloseSession(session);
            }
            //empName, addr,deptid
            return true;
        }

        public List<EmployeeDTO> GetAllEmployeeDetail()
        {
            List<EmployeeDTO> empDTO = new List<EmployeeDTO>();
            ISession session = null;
            ITransaction transaction = null;
            IList lst = null;
            try
            {
                session = NHibernateUtil.OpenSession();
                if (null == session)
                {
                    throw new Exception("No Session created!!!");
                }
                transaction = session.BeginTransaction();
                string hql = "from EmployeeDTO";
                IQuery query = session.CreateQuery(hql);
                lst = query.List();
                //session.SaveOrUpdate(empDTO);
                if (lst != null)
                {
                    foreach (var item in lst)
                    {
                        empDTO.Add(new EmployeeDTO(){
                            Address = ((EmployeeDTO)item).Address,
                            Id = ((EmployeeDTO)item).Id,
                            Name = ((EmployeeDTO)item).Name
                        });
                    }
                }
                transaction.Commit();
            }
            catch (Exception e)
            {
                //return lst;
            }
            finally
            {
                NHibernateUtil.CloseSession(session);
            }
            return empDTO;
        }
    }
}
